package com.bckj.fastboot.iot.data.mysql.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.bckj.fastboot.iot.common.dto.query.IotBasicDataQuery;
import com.bckj.fastboot.iot.common.dto.response.IotBasicDataResponse;
import com.bckj.fastboot.iot.data.mysql.entity.IotBasicData;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * IotBasicDataMapper
 *
 * @author wfc
 * @date 2025/9/25 14:58
 **/
@Mapper
public interface IotBasicDataMapper extends BaseMapper<IotBasicData> {

    @Results(id = "BasicDataResultMap", value = {
            @Result(column = "data_value", property = "dataMap", typeHandler = JacksonTypeHandler.class)
    })
    @SelectProvider(type = IotBasicDataProvider.class, method = "findList")
    List<IotBasicDataResponse> findList(IotBasicDataQuery query);

    @ResultMap("BasicDataResultMap")
    @Select("""
    select * from iot_basic_data
    where id=#{id}
    """)
    IotBasicDataResponse findById(Long id);

    class IotBasicDataProvider {
        public String findList(IotBasicDataQuery query) {
            SQL sql = new SQL();
            sql.SELECT("bd.*");
            sql.FROM("iot_basic_data bd");
            listWhere(sql, query);
            return sql.toString();
        }

        private void listWhere(SQL sql, IotBasicDataQuery query) {
            if (StringUtils.hasText(query.getDevCode())) {
                sql.WHERE("bd.dev_code = #{devCode}");
            }
            if (query.getStartTime() != null) {
                sql.WHERE("bd.create_time >= #{startTime}");
            }
            if (query.getEndTime() != null) {
                sql.WHERE("bd.create_time <= #{endTime}");
            }
        }
    }
}
